package lion.crawl.rule;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lion.dev.lang.MapJ;

/**
 * @author Helin
 * @date 2012-8-16
 * @email hl_0074@sina.com
 * @desc 正则解析器
 */
public class RegexFieldRule implements ParseRule {

	private String name;
	private String fieldName;
	private String pattern;
	private Pattern p;

	public RegexFieldRule() {
	}

	public RegexFieldRule(String fieldName, String pattern) {

		this(fieldName, fieldName, pattern);
	}

	public RegexFieldRule(String name, String fieldName, String pattern) {

		this.name = name;
		this.fieldName = fieldName;
		this.pattern = pattern;
		try {
			this.p = Pattern.compile(pattern);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void extract(String content, MapJ result) {

		Matcher m = this.p.matcher(content);

		List<String> eles = new ArrayList<String>();

		int end = 0;
		while (m.find(end)) {
			if (m.groupCount() > 0) {
				eles.add(m.group(1));
			} else {
				eles.add(m.group());
			}
			end = m.end();
		}
		result.put(this.fieldName, eles);
	}

	public String getName() {

		return this.name;
	}

	public void setName(String name) {

		this.name = name;
	}

	public String getFieldName() {

		return this.fieldName;
	}

	public void setFieldName(String field) {

		this.fieldName = field;
	}

	public String getPattern() {

		return pattern;
	}

	public void setPattern(String pattern) {

		this.pattern = pattern;
		this.p = Pattern.compile(pattern);
	}
}